package service

import (
	"im/global"
	"im/mapper"
	"im/model"
	"im/model/request"
	"im/model/response"
	"im/utils"

	"github.com/gin-gonic/gin"
)

type ChatGroupService struct{}

// 添加群
func (cga *ChatGroupService) AddGroup(c *gin.Context) {
	var chatGroupReq request.ChatGroupReq
	if err := c.ShouldBind(&chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("请求体解析失败", c)
		c.Abort()
	}

	// Todo: 校验参数
	// 获取当前用户id
	if uid, err := utils.ParseTokenToUserId(c); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("Token解析错误", c)
		c.Abort()
	} else {
		chatGroupReq.OwnerId = uid
	}
	if u, err := mapper.AddGroup(chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("新增群信息失败", c)
	} else {
		response.Result(global.StatusOK, u, "操作成功", c)
	}
	c.Abort()
}

// 更新群信息
func (cga *ChatGroupService) UpdateGroup(c *gin.Context) {
	var chatGroup model.ChatGroup
	if err := c.ShouldBind(&chatGroup); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("请求体解析失败", c)
		c.Abort()
	}

	// Todo: 校验参数
	// 获取当前用户id
	if uid, err := utils.ParseTokenToUserId(c); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("Token解析错误", c)
		c.Abort()
	} else {
		chatGroup.OwnerId = uid
	}
	if u, err := mapper.UpdateGroup(chatGroup); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("修改群消息失败", c)
	} else {
		response.Result(global.StatusOK, u, "更新成功", c)
	}
	c.Abort()
}

// 获取群列表(群主)
/**
param1: ownerId
param2: name (非必传)
*/
func (cga *ChatGroupService) ListGroups(c *gin.Context) {
	var chatGroupReq request.ChatGroupReq
	if err := c.ShouldBind(&chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("请求体解析失败", c)
		c.Abort()
	}

	// Todo: 校验参数
	// 获取当前用户id
	if uid, err := utils.ParseTokenToUserId(c); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("Token解析错误", c)
		c.Abort()
	} else {
		chatGroupReq.OwnerId = uid
	}
	if u, err := mapper.ListGroups(chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("获取群列表失败", c)
	} else {
		response.Result(global.StatusOK, u, "获取群列表成功", c)
	}
	c.Abort()
}

// 删除群信息
/**
param1: id:群id (必传)
param2: ownerId: 群拥有者id
*/
func (cga *ChatGroupService) DelGroup(c *gin.Context) {
	var chatGroupReq request.ChatGroupReq
	if err := c.ShouldBind(&chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("请求体解析失败", c)
		c.Abort()
	}

	// Todo: 校验参数
	// 获取当前用户id
	if uid, err := utils.ParseTokenToUserId(c); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("Token解析错误", c)
		c.Abort()
	} else {
		chatGroupReq.OwnerId = uid
	}
	if u, err := mapper.DelGroup(chatGroupReq); err != nil {
		// global.LOG.Error(err.Error())
		response.FailWithMessage("删除群信息失败", c)
	} else {
		response.Result(global.StatusOK, u, "操作成功", c)
	}
	c.Abort()
}
